package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private ShoppingCartController shoppingCartController;
    @Autowired
    private ShoppingCartService shoppingCartService;
    /**
     * 用户下单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 后端查询订单
     */

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime) {

        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number != null, Orders::getNumber, number)
                .gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime)
                .lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime);

        orderService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
    * 用户订单分页查询
    */
    @GetMapping("userPage")
    public R<Page> page( int page ,int pageSize){

        Page<Orders> pageInfo=new Page<>(page,pageSize);
        Page<OrdersDto> dtoPage=new Page<>();
        LambdaQueryWrapper<Orders> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,BaseContext.getCurrentId());

        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo,lqw);

        LambdaQueryWrapper<OrderDetail> queryWrapper2=new LambdaQueryWrapper<>();
        List<Orders> records = pageInfo.getRecords();
        List<OrdersDto> list=records.stream().map(item->{
            OrdersDto ordersDto=new OrdersDto();
            Long orderId = item.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,orderId);
            List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
            BeanUtils.copyProperties(item,ordersDto);
            ordersDto.setOrderDetails(orderDetailList);
            return ordersDto;
        }).collect(Collectors.toList());
        BeanUtils.copyProperties(pageInfo,dtoPage,"records");
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }
    /*public List<OrderDetail> getOrderDetailListByOrderId(Long orderId){

    }*/

    /**
     * 修改后台订单状态
     */
    @PutMapping
    public R<String> orderStatusChange(@RequestBody Map<String, String> map){
        String id = map.get("id");
        long orderId = Long.parseLong(id);
        Integer status = Integer.parseInt(map.get("status"));

        if (id ==null ||status==null){
            return R.error("输入错误");
        }
        Orders orders = orderService.getById(orderId);
        orders.setStatus(status);
        orderService.updateById(orders);
        return R.success("修改成功!");
    }


    /**
     * 客户端点击再来一单
     */
    @PostMapping("/again")
    public R<String> againSubmit(@RequestBody Map<String,String> map){
        String ids = map.get("id");
        long id = Long.parseLong(ids);

        LambdaQueryWrapper<OrderDetail> lqw=new LambdaQueryWrapper<>();
        lqw.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(lqw);

        shoppingCartController.clean();
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList=list.stream().map(item->{
            ShoppingCart shoppingCart=new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId !=null){
                shoppingCart.setDishId(dishId);
            }else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCartList);
        return R.success("操作成功!");
    }
}
